package com.edu.whu.service.impl;

import com.edu.whu.dao.UserInfoJpaRepository;
import com.edu.whu.entity.UserInfo;
import com.edu.whu.entity.UserInfoDto;
import com.edu.whu.service.ServiceException;
import com.edu.whu.service.TokenUserService;
import com.edu.whu.service.UserService;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    private final UserInfoJpaRepository userInfoJpaRepository;
    private final TokenUserService tokenUserService;



    public UserServiceImpl(UserInfoJpaRepository userInfoJpaRepository, TokenUserService tokenUserService) {
        this.userInfoJpaRepository = userInfoJpaRepository;
        this.tokenUserService = tokenUserService;

    }

    @Override
    public String createUser(UserInfo userInfo) throws ServiceException {
        if (userInfoJpaRepository.existsById(userInfo.getAccount())) {
            throw new ServiceException("账号已存在");
        } else {
            userInfo.validate();
            userInfoJpaRepository.save(userInfo);
            return tokenUserService.acquireToken(userInfo.getAccount());
        }
    }

    @Override
    public UserInfoDto getUser(String account) {
        UserInfo userInfo = userInfoJpaRepository.findById(account).orElse(null);
        if (userInfo == null) {
            return null;
        } else {
            return new UserInfoDto.Builder().withAccount(userInfo.getAccount()).withName(userInfo.getName()).build();
        }
    }


    @Override
    public String login(UserInfo userInfo)throws ServiceException {
        String account = userInfo.getAccount();
        String password = userInfo.getPassword();
        if (userInfoJpaRepository.findByAccount(account) == null) {
            throw new ServiceException("账户不存在！");
        } else {
            UserInfo u = userInfoJpaRepository.findByAccount(account);
            if (Objects.equals(u.getPassword(), password)) {
                return tokenUserService.acquireToken(u.getAccount());
            } else {
                throw new ServiceException("密码错误，请重试！");
            }
        }
    }
}
